/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ImageCache;

import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import javax.microedition.lcdui.Image;

/**
 *
 * @author SamSung
 */
public final class ImageCache {

    private static ImageCache instance;
    private static final String IMAGES_RS = "ImageList";
    private Hashtable images = new Hashtable();
    private ImageCacheListener listener;
    private String thPngUri;
    private static final int EXPIRE_TIME_SECS = 60 * 60 * 24 * 3;

    private ImageCache() {
    }

    synchronized public static ImageCache getInstance() {
        if (instance == null) {
            instance = new ImageCache();
        }
        return instance;
    }

    public void setListenner(ImageCacheListener listener) {
        this.listener = listener;
    }

//    public boolean isImageLoaded(String resourceName) {
//        return images.get(resourceName) != null;
//    }
    public Image getImageResource(String resourceName) {
        Image img = null;
        // Try to load from memory
        img = (Image) images.get(resourceName);
        // If not in memory, load from RMS, network, in that order
        if (img == null) {
//             Try to load from RMS
            img = ImageRmsUtils.loadPngFromRMS(IMAGES_RS, resourceName);
            if (img != null) {
//                // Keep track of loaded Images
                images.put(resourceName, img);
            }
//            else {
//                // If not in RMS, try to load over the network
//                // dispatch network retrieval
//                getImageOverHttp(resourceName); // name is URi
//            }
        }
        return img; // returns null for network retrievals
    }

    public Image loadImageFromRMS(String resourceName) {
        Image img = null;
        img = ImageRmsUtils.loadPngFromRMS(IMAGES_RS, resourceName);
        return img;
    }

    public void clearImageCache() {
        ImageRmsUtils.clearImageRecordStore(IMAGES_RS);
        images.clear();
    }

    public int expireCache(int expireSeconds) {
        return ImageRmsUtils.clearExpiredImages(
                IMAGES_RS,
                ((expireSeconds > 0) ? expireSeconds : EXPIRE_TIME_SECS));
    }

    synchronized public void getImageOverHttp(String pngUri) {
        System.out.println(pngUri);
        thPngUri = pngUri; // set class-wide member, used by thread
        InputStream is = null;
        try {
            is = NetworkUtils.getResourceOverHTTP(
                    thPngUri, NetworkUtils.MIMETYPE_IMAGE_PNG);
        } catch (IOException ioe) {
            // Log error, return
            return;
        }
        notifyHttpPngRetrievalComplete(thPngUri, is);

        thPngUri = null;
        is = null;
        System.gc();
    }

    synchronized private void notifyHttpPngRetrievalComplete(
            String resourceName, InputStream pngInputStream) {
        System.out.println("pp");
        // Create Image from input stream, add it to image collection
        if (pngInputStream != null) {
            Image pngImage = null;
            try {
                // Creates image from decoded image data obtained
                //  from an InputStream. After this method completes
                //  the stream is left open and its current position
                //  is undefined.
                pngImage = Image.createImage(pngInputStream);
                // Keep track of loaded Images

                images.put(resourceName, pngImage);


                // Save PngImage into RMS.
                //  Note that input stream is null if PNG
                // retrieval was unsuccessful.
                ImageRmsUtils.savePngImage(
                        IMAGES_RS, resourceName, pngImage);
                if (listener != null) {
                    listener.onEvent(
                            ImageCacheListener.EVENT_LOADED,
                            resourceName,
                            pngImage);
                }

            } catch (IOException ioe) {
                // Log error
            } finally {
                pngImage = null;
                System.gc();
                // Close after use
                if (pngInputStream != null) {
                    try {
                        pngInputStream.close();
                    } catch (IOException ignore) {
                        // ignore
                    }
                }
                System.gc();
            }

        }
    }
}
